import { useState, useEffect, useCallback } from 'react';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { API_ENDPOINTS } from '@/config/api';
import toast from 'react-hot-toast';

export interface BlockchainEvent {
  id: string;
  event_type: string;
  contract_address: string;
  block_number: number;
  tx_hash: string;
  from_address: string;
  to_address?: string;
  amount?: string;
  timestamp: string;
  is_processed: boolean;
  created_at: string;
}

export const useEventNotifications = (enabled = false) => {
  const { currentChain } = useChain();
  const [lastEventId, setLastEventId] = useState<string | null>(null);
  const [newEventsCount, setNewEventsCount] = useState(0);
  const [isPolling, setIsPolling] = useState(enabled);

  const checkForNewEvents = useCallback(async () => {
    if (!isPolling) return;

    try {
      // 獲取最新的5個事件
      const response = await multiChainApi.getClient(currentChain).get(API_ENDPOINTS.blockchainEvents.list, {
        params: {
          limit: 5,
          offset: 0
        }
      });

      const events: BlockchainEvent[] = response.data;
      
      if (events.length > 0) {
        const latestEvent = events[0];
        
        // 如果這是我們第一次檢查，或者有新事件
        if (lastEventId && latestEvent.id !== lastEventId) {
          // 計算新事件數量
          const newEventIndex = events.findIndex(event => event.id === lastEventId);
          const newCount = newEventIndex === -1 ? events.length : newEventIndex;
          
          if (newCount > 0) {
            setNewEventsCount(prev => prev + newCount);
            
            // 顯示新事件通知
            const newEvents = events.slice(0, newCount);
            newEvents.forEach(event => {
              const message = getEventNotificationMessage(event);
              
              // 根據事件類型顯示不同的通知
              if (event.event_type.includes('Error') || event.event_type.includes('Failed')) {
                toast.error(message, { duration: 5000 });
              } else if (event.event_type.includes('Released') || event.event_type.includes('Claimed')) {
                toast.success(message, { duration: 4000 });
              } else {
                toast(message, { 
                  duration: 3000,
                  icon: '🔗'
                });
              }
            });
          }
        }
        
        setLastEventId(latestEvent.id);
      }
    } catch (error) {
      console.error('Failed to check for new events:', error);
    }
  }, [isPolling, lastEventId, currentChain]);

  const getEventNotificationMessage = (event: BlockchainEvent): string => {
    const shortTxHash = `${event.tx_hash.slice(0, 8)}...${event.tx_hash.slice(-6)}`;
    const shortFromAddress = `${event.from_address.slice(0, 6)}...${event.from_address.slice(-4)}`;
    
    switch (event.event_type) {
      case 'MiningStarted':
        return `🔥 新的挖礦開始: ${shortFromAddress} (${shortTxHash})`;
      case 'MiningClaimed':
        return `💰 挖礦獎勵領取: ${event.amount || 'N/A'} DTV (${shortTxHash})`;
      case 'TokensReleased':
        return `🎯 代幣釋放: ${event.amount || 'N/A'} DTV (${shortTxHash})`;
      case 'VestingScheduleCreated':
        return `📋 新建歸屬計劃: ${shortFromAddress} (${shortTxHash})`;
      case 'VestingRevoked':
        return `❌ 歸屬計劃撤銷: ${shortTxHash}`;
      case 'NFTMinted':
        return `🖼️ NFT 鑄造: ${shortFromAddress} (${shortTxHash})`;
      case 'Transfer':
        return `💸 代幣轉移: ${event.amount || 'N/A'} DTV (${shortTxHash})`;
      default:
        return `🔗 新區塊鏈事件: ${event.event_type} (${shortTxHash})`;
    }
  };

  const clearNewEventsCount = useCallback(() => {
    setNewEventsCount(0);
  }, []);

  const togglePolling = useCallback(() => {
    setIsPolling(prev => !prev);
  }, []);

  // 定期檢查新事件
  useEffect(() => {
    if (!isPolling) return;

    // 立即檢查一次
    checkForNewEvents();

    // 每15秒檢查一次新事件
    const interval = setInterval(checkForNewEvents, 15000);

    return () => clearInterval(interval);
  }, [isPolling, checkForNewEvents]);

  return {
    newEventsCount,
    isPolling,
    clearNewEventsCount,
    togglePolling,
    checkForNewEvents
  };
};